package com.shuai.chatroom.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuai.chatroom.common.AppConstant;
import com.shuai.chatroom.common.HttpResult;
import com.shuai.chatroom.common.UserSessionUtils;
import com.shuai.chatroom.config.UserOnLineStateManager;
import com.shuai.chatroom.entity.MessageInfo;
import com.shuai.chatroom.entity.UserInfo;
import com.shuai.chatroom.entity.vo.FriendInfoVO;
import com.shuai.chatroom.entity.vo.MessageInfoVO;
import com.shuai.chatroom.exception.ControllerException;
import com.shuai.chatroom.exception.ServiceException;
import com.shuai.chatroom.service.MessageService;
import com.shuai.chatroom.service.SessionsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource
    private MessageService messageService;

    @Resource
    private UserOnLineStateManager userOnLineStateManager;
    @Resource
    private ObjectMapper objectMapper = new ObjectMapper();


    @Resource
    private SessionsService sessionsService;

    @RequestMapping("/detail")
    public HttpResult getHistoryMessageList(Integer sessionId) throws ControllerException {
        if (sessionId == null) {
            throw new ControllerException("非法参数！");
        }
        return HttpResult.success(messageService.getHistoryMessageList(sessionId));
    }

    @RequestMapping("/get_dn_num")
    public HttpResult getNoReadMessNum(Integer sessionId, HttpServletRequest request) throws ControllerException {
        if (sessionId == null) {
            throw new ControllerException("非法参数！");
        }
        UserInfo userInfo = (UserInfo) request.getSession(false).getAttribute(AppConstant.USER_SESSION_KEY);
        if (userInfo == null || userInfo.getUId() == null) {
            throw new ControllerException("非法请求！");
        }
        return HttpResult.success(200, messageService.getNoReadMessNum(sessionId, userInfo.getUId()));
    }


    @RequestMapping("/update_state")
    public HttpResult updateMessState(Integer sessionId) throws ControllerException {
        if (sessionId == null) {
            throw new ControllerException("非法参数！");
        }
        messageService.updateMessState(sessionId);
        return HttpResult.success(200);
    }

    @RequestMapping("/up_file")
    public HttpResult uploadFile(@RequestPart("fileData") MultipartFile file, @RequestParam("sessionId") Integer sessionId, HttpServletRequest request) throws ControllerException, ServiceException, IOException {
        if (sessionId == null) {
            throw new ControllerException("非法参数！");
        }
        UserInfo userInHttpSession = UserSessionUtils.getUserInHttpSession(request);
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setFromUId(userInHttpSession.getUId());
        messageInfo.setIsRead(0);
        messageInfo.setSessionId(sessionId);
        String visitPath = messageService.uploadFile(file, messageInfo);
        //如果用户在线，将消息直接推送给用户(TODO:这里可以再封装一个方法)
        List<FriendInfoVO> friendsList = sessionsService.getFriendsList(sessionId, userInHttpSession.getUId());
        FriendInfoVO myself = new FriendInfoVO();
        myself.setFId(userInHttpSession.getUId());
        myself.setFriendName(userInHttpSession.getUsername());
        myself.setFriendPhoto(userInHttpSession.getPhoto());
        myself.setFriendNickname(userInHttpSession.getNickname());
        myself.setSessionId(sessionId);
        friendsList.add(myself);
        //构建消息响应对象
        MessageInfoVO messageInfoVO = new MessageInfoVO();
        messageInfoVO.setOriginalFileName(file.getOriginalFilename());
        messageInfoVO.setMessType(AppConstant.MESSAGE_TYPE_FILE);
        messageInfoVO.setMessContent(visitPath);
        messageInfoVO.setCreateTime(LocalDateTime.now());
        messageInfoVO.setSessionId(sessionId);
        messageInfoVO.setUsername(userInHttpSession.getUsername());
        messageInfoVO.setNickname(userInHttpSession.getNickname());
        messageInfoVO.setFriendPhoto(userInHttpSession.getPhoto());
        messageInfoVO.setFromUId(userInHttpSession.getUId());
        for (FriendInfoVO friendInfoVO : friendsList) {
            WebSocketSession userSession = userOnLineStateManager.getUserSession(friendInfoVO.getFId());
            if (userSession == null) {
                continue;
            }
            userSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(messageInfoVO)));
        }
        return HttpResult.success(200); //上传文件成功！
    }
}
